<template>
  <div class="updatePwd">
    <el-card shadow="never">
      <template #header>
        <div class="header">
          <span>重置密码</span>
        </div>
      </template>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="原密码" prop="old_pwd" >
          <el-input v-model="form.old_pwd" disabled style="width: 400px"/>
        </el-form-item>
        <el-form-item label="新密码" prop="new_pwd">
          <el-input v-model="form.new_pwd" placeholder="请输入新密码" style="width: 400px"/>
        </el-form-item>
        <el-form-item label="确认新密码" prop="re_pwd">
          <el-input v-model="form.re_pwd" placeholder="再次输入新密码" style="width: 400px" />
        </el-form-item>
        <el-form-item>
          <template>
            <el-button @click="submit" type="primary">修改密码</el-button>
            <el-button @click="reset" type="primary" plain>重置</el-button>
          </template>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { updatePwd } from '@/api/user'
export default {
  name: 'updatePwd-page',
  data () {
    const validateRepwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.new_pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      form: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rules: {
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: ['blur', 'change'] },
          { min: 6, max: 15, message: '请输入6~15个字符', trigger: ['blur', 'change'] }
        ],
        re_pwd: [{ validator: validateRepwd, trigger: ['blur', 'change'] }]
      }
    }
  },
  async created () {
    this.initData()
  },
  methods: {
    async initData () {
      this.form.old_pwd = this.$store.state.user.password
    },
    async submit () {
      await this.$refs.form.validate()
      const res = await updatePwd(this.form)
      console.log(res)
      this.$message.success('更新密码成功！')
    },
    reset () {
      this.form.new_pwd = ''
      this.form.re_pwd = ''
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
    span {
      font-size: 16px;
      color: #131523;
      font-weight: 500;
    }
  }
}
</style>
